package com.leemz.design.chapter4.none;

import java.io.*;
import java.util.List;

public class LogFileOperate implements LogFileOperateApi {

    private String logFile = "AdapterLog.log";

    public LogFileOperate(String logFile) {
        if(null != logFile && logFile.length() > 0) {
            this.logFile = logFile;
        }
    }

    @Override
    public List<LogModel> readLogFile() {
        List<LogModel> list = null;
        ObjectInputStream ois = null;
        try {
            File file = new File(logFile);
            if(file.exists()) {
                ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream(file)));
                list = (List<LogModel>) ois.readObject();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(ois != null) {
                try {
                    ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return list;
    }

    @Override
    public void writeLogFile(List<LogModel> list) {
        ObjectOutputStream oos = null;
        try {
            File file = new File(logFile);
            oos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
            oos.writeObject(list);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(null != oos) {
                try {
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
